﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace FileUploadBench
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }

        private void btn_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Multiselect = false;
            if ((bool)dlg.ShowDialog())
            {
                txtStatus.Text = dlg.SelectedFile.Name;
                UploadFile(dlg.SelectedFile.Name, dlg.SelectedFile.OpenRead());
            } else
            {
                txtStatus.Text = "No selected Files...";
            }
        }

        private void UploadFile(string name, Stream stream)
        {
            UriBuilder uriBuilder = new UriBuilder("http://localhost:9722/FileReceiver.ashx");
            uriBuilder.Query = string.Format("filename={0}", name);

            WebClient client = new WebClient();
            client.OpenWriteCompleted += (sender, e) =>
            {
                PushData(stream, e.Result);
                e.Result.Close();
                stream.Close();
            };
            client.OpenWriteAsync(uriBuilder.Uri);
        }

        private void PushData(Stream input, Stream output)
        {
            byte[] buffer = new byte[4096];
            int bytesread;

            while ((bytesread = input.Read(buffer,0,buffer.Length)) != 0)
            {
                output.Write(buffer,0,bytesread);
            }
        }

    }
}
